

import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, Modal, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface ApprovalItem {
  id: string;
  title: string;
  status: 'processing' | 'completed' | 'rejected' | 'cancelled';
  currentNode: string;
  startTime: string;
  priority: 'high' | 'normal' | 'low';
}

interface FilterOptions {
  status: 'all' | 'processing' | 'completed' | 'rejected' | 'cancelled';
  sort: 'time_desc' | 'time_asc';
  search: string;
}

const MyInitiatedScreen = () => {
  const router = useRouter();
  
  // 模拟数据
  const mockApprovals: ApprovalItem[] = [
    {
      id: 'PI001',
      title: '员工请假申请',
      status: 'processing',
      currentNode: '部门经理审批',
      startTime: '2024-01-15 09:30',
      priority: 'normal'
    },
    {
      id: 'PI002',
      title: '采购申请单',
      status: 'completed',
      currentNode: '已完成',
      startTime: '2024-01-14 14:20',
      priority: 'high'
    },
    {
      id: 'PI003',
      title: '差旅报销申请',
      status: 'rejected',
      currentNode: '财务审批',
      startTime: '2024-01-13 16:45',
      priority: 'normal'
    },
    {
      id: 'PI004',
      title: '办公用品申请',
      status: 'processing',
      currentNode: '行政审批',
      startTime: '2024-01-12 11:15',
      priority: 'low'
    },
    {
      id: 'PI005',
      title: '加班申请',
      status: 'completed',
      currentNode: '已完成',
      startTime: '2024-01-11 18:30',
      priority: 'normal'
    },
    {
      id: 'PI006',
      title: '培训申请',
      status: 'cancelled',
      currentNode: '已取消',
      startTime: '2024-01-10 10:00',
      priority: 'normal'
    }
  ];

  const [approvalList, setApprovalList] = useState<ApprovalItem[]>([]);
  const [filteredApprovals, setFilteredApprovals] = useState<ApprovalItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const [isFilterModalVisible, setIsFilterModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filterOptions, setFilterOptions] = useState<FilterOptions>({
    status: 'all',
    sort: 'time_desc',
    search: ''
  });

  // 获取状态文本
  const getStatusText = (status: string) => {
    const texts = {
      'processing': '审批中',
      'completed': '已完成',
      'rejected': '已驳回',
      'cancelled': '已取消'
    };
    return texts[status as keyof typeof texts] || '审批中';
  };

  // 获取优先级文本
  const getPriorityText = (priority: string) => {
    const texts = {
      'high': '高优先级',
      'low': '低优先级'
    };
    return texts[priority as keyof typeof texts] || '普通';
  };

  // 格式化时间显示
  const formatTime = (timeString: string) => {
    const now = new Date();
    const time = new Date(timeString);
    const diffMs = now.getTime() - time.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffHours / 24);

    if (diffHours < 1) {
      return '刚刚';
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return time.toLocaleDateString('zh-CN');
    }
  };

  // 筛选和排序数据
  const filterAndSortData = useCallback(() => {
    let filtered = [...approvalList];

    // 搜索筛选
    if (filterOptions.search) {
      filtered = filtered.filter(approval => 
        approval.title.toLowerCase().includes(filterOptions.search.toLowerCase())
      );
    }

    // 状态筛选
    if (filterOptions.status !== 'all') {
      filtered = filtered.filter(approval => approval.status === filterOptions.status);
    }

    // 排序
    filtered.sort((a, b) => {
      const aTime = new Date(a.startTime);
      const bTime = new Date(b.startTime);
      return filterOptions.sort === 'time_desc' ? bTime.getTime() - aTime.getTime() : aTime.getTime() - bTime.getTime();
    });

    setFilteredApprovals(filtered);
  }, [approvalList, filterOptions]);

  // 加载数据
  const loadApprovalData = useCallback(async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setApprovalList(mockApprovals);
    } catch (error) {
      Alert.alert('错误', '加载数据失败，请重试');
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      await loadApprovalData();
    } finally {
      setIsRefreshing(false);
    }
  }, [loadApprovalData]);

  // 搜索切换
  const handleSearchToggle = () => {
    setIsSearchVisible(!isSearchVisible);
    if (isSearchVisible) {
      setSearchText('');
      setFilterOptions(prev => ({ ...prev, search: '' }));
    }
  };

  // 搜索输入
  const handleSearchChange = (text: string) => {
    setSearchText(text);
    setFilterOptions(prev => ({ ...prev, search: text }));
  };

  // 清除搜索
  const handleClearSearch = () => {
    setSearchText('');
    setFilterOptions(prev => ({ ...prev, search: '' }));
  };

  // 筛选状态选择
  const handleStatusFilter = (status: FilterOptions['status']) => {
    setFilterOptions(prev => ({ ...prev, status }));
  };

  // 排序选择
  const handleSortChange = (sort: FilterOptions['sort']) => {
    setFilterOptions(prev => ({ ...prev, sort }));
  };

  // 重置筛选
  const handleResetFilters = () => {
    setFilterOptions({
      status: 'all',
      sort: 'time_desc',
      search: ''
    });
    setSearchText('');
  };

  // 清除所有筛选
  const handleClearAllFilters = () => {
    handleResetFilters();
    setIsSearchVisible(false);
  };

  // 审批项点击
  const handleApprovalItemPress = (processInstanceId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${processInstanceId}`);
  };

  // 渲染审批项
  const renderApprovalItem = ({ item }: { item: ApprovalItem }) => (
    <TouchableOpacity
      style={styles.approvalItem}
      onPress={() => handleApprovalItemPress(item.id)}
      activeOpacity={0.8}
    >
      <LinearGradient
        colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.approvalItemGradient}
      >
        <View style={styles.approvalItemHeader}>
          <Text style={styles.approvalItemTitle} numberOfLines={1}>
            {item.title}
          </Text>
          <LinearGradient
            colors={
              item.status === 'processing' ? ['#f59e0b', '#d97706'] :
              item.status === 'completed' ? ['#10b981', '#059669'] :
              item.status === 'rejected' ? ['#ef4444', '#dc2626'] :
              ['#6b7280', '#4b5563']
            }
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 0 }}
            style={styles.statusBadge}
          >
            <Text style={styles.statusBadgeText}>{getStatusText(item.status)}</Text>
          </LinearGradient>
        </View>
        
        <View style={styles.approvalItemInfo}>
          <View style={styles.approvalItemInfoLeft}>
            <FontAwesome6 name="location-dot" size={12} color="rgba(99, 102, 241, 0.7)" />
            <Text style={styles.approvalItemInfoText}>{item.currentNode}</Text>
          </View>
          <View style={styles.approvalItemInfoRight}>
            <FontAwesome6 name="clock" size={12} color="rgba(99, 102, 241, 0.7)" />
            <Text style={styles.approvalItemInfoText}>{formatTime(item.startTime)}</Text>
          </View>
        </View>
        
        <View style={styles.approvalItemFooter}>
          <Text style={styles.approvalItemTimeText}>发起时间：{item.startTime}</Text>
          {item.priority !== 'normal' && (
            <View style={[
              styles.priorityBadge,
              { backgroundColor: item.priority === 'high' ? '#ef4444' : '#6b7280' }
            ]}>
              <Text style={styles.priorityBadgeText}>{getPriorityText(item.priority)}</Text>
            </View>
          )}
        </View>
      </LinearGradient>
    </TouchableOpacity>
  );

  // 渲染空状态
  const renderEmptyState = () => (
    <View style={styles.emptyStateContainer}>
      <LinearGradient
        colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.emptyStateGradient}
      >
        <FontAwesome6 name="file-lines" size={48} color="#6b7280" />
        <Text style={styles.emptyStateTitle}>暂无发起记录</Text>
        <Text style={styles.emptyStateSubtitle}>您还没有发起过任何审批</Text>
      </LinearGradient>
    </View>
  );

  // 渲染筛选标签
  const renderFilterTags = () => {
    if (filterOptions.status === 'all' && !filterOptions.search) {
      return null;
    }

    return (
      <View style={styles.filterTagsContainer}>
        <Text style={styles.filterTagsLabel}>筛选：</Text>
        <View style={styles.activeFiltersContainer}>
          {filterOptions.status !== 'all' && (
            <View style={styles.filterTag}>
              <Text style={styles.filterTagText}>{getStatusText(filterOptions.status)}</Text>
              <TouchableOpacity
                onPress={() => handleStatusFilter('all')}
                style={styles.filterTagRemove}
              >
                <FontAwesome6 name="xmark" size={10} color="rgba(99, 102, 241, 0.7)" />
              </TouchableOpacity>
            </View>
          )}
          {filterOptions.search && (
            <View style={[styles.filterTag, styles.searchFilterTag]}>
              <Text style={[styles.filterTagText, styles.searchFilterTagText]}>
                搜索: "{filterOptions.search}"
              </Text>
              <TouchableOpacity
                onPress={handleClearSearch}
                style={styles.filterTagRemove}
              >
                <FontAwesome6 name="xmark" size={10} color="rgba(139, 92, 246, 0.7)" />
              </TouchableOpacity>
            </View>
          )}
        </View>
        <TouchableOpacity onPress={handleClearAllFilters}>
          <Text style={styles.clearFiltersText}>清除筛选</Text>
        </TouchableOpacity>
      </View>
    );
  };

  useEffect(() => {
    loadApprovalData();
  }, [loadApprovalData]);

  useEffect(() => {
    filterAndSortData();
  }, [filterAndSortData]);

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.loadingContainer}>
          <FontAwesome6 name="spinner" size={24} color="#6366f1" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <LinearGradient
            colors={['#6366f1', '#8b5cf6']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 0 }}
            style={styles.titleGradient}
          >
            <Text style={styles.titleText}>我发起的</Text>
          </LinearGradient>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={handleSearchToggle}
            >
              <FontAwesome6 name="magnifying-glass" size={18} color="#9ca3af" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={() => setIsFilterModalVisible(true)}
            >
              <FontAwesome6 name="filter" size={18} color="#9ca3af" />
            </TouchableOpacity>
          </View>
        </View>

        {/* 搜索框 */}
        {isSearchVisible && (
          <View style={styles.searchContainer}>
            <View style={styles.searchInputWrapper}>
              <FontAwesome6 name="magnifying-glass" size={16} color="#9ca3af" style={styles.searchIcon} />
              <TextInput
                style={styles.searchInput}
                placeholder="搜索审批标题..."
                placeholderTextColor="#9ca3af"
                value={searchText}
                onChangeText={handleSearchChange}
                autoFocus
              />
              {searchText.length > 0 && (
                <TouchableOpacity
                  style={styles.searchClearButton}
                  onPress={handleClearSearch}
                >
                  <FontAwesome6 name="xmark" size={14} color="#9ca3af" />
                </TouchableOpacity>
              )}
            </View>
          </View>
        )}
      </View>

      {/* 筛选标签 */}
      {renderFilterTags()}

      {/* 审批列表 */}
      <FlatList
        data={filteredApprovals}
        renderItem={renderApprovalItem}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor="#6366f1"
            colors={['#6366f1']}
          />
        }
        ListEmptyComponent={renderEmptyState}
      />

      {/* 筛选弹窗 */}
      <Modal
        visible={isFilterModalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setIsFilterModalVisible(false)}
      >
        <View style={styles.filterModalOverlay}>
          <View style={styles.filterModalContainer}>
            <View style={styles.filterModalHeader}>
              <Text style={styles.filterModalTitle}>筛选条件</Text>
              <TouchableOpacity
                onPress={() => setIsFilterModalVisible(false)}
                style={styles.filterModalCloseButton}
              >
                <FontAwesome6 name="xmark" size={20} color="#9ca3af" />
              </TouchableOpacity>
            </View>

            {/* 状态筛选 */}
            <View style={styles.filterSection}>
              <Text style={styles.filterSectionTitle}>审批状态</Text>
              <View style={styles.filterStatusContainer}>
                {[
                  { key: 'all', label: '全部' },
                  { key: 'processing', label: '审批中' },
                  { key: 'completed', label: '已完成' },
                  { key: 'rejected', label: '已驳回' },
                  { key: 'cancelled', label: '已取消' }
                ].map((status) => (
                  <TouchableOpacity
                    key={status.key}
                    style={[
                      styles.filterStatusButton,
                      filterOptions.status === status.key && styles.filterStatusButtonActive
                    ]}
                    onPress={() => handleStatusFilter(status.key as FilterOptions['status'])}
                  >
                    <Text style={[
                      styles.filterStatusButtonText,
                      filterOptions.status === status.key && styles.filterStatusButtonTextActive
                    ]}>
                      {status.label}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>

            {/* 排序方式 */}
            <View style={styles.filterSection}>
              <Text style={styles.filterSectionTitle}>排序方式</Text>
              <View style={styles.filterSortContainer}>
                {[
                  { key: 'time_desc', label: '按时间倒序' },
                  { key: 'time_asc', label: '按时间正序' }
                ].map((sort) => (
                  <TouchableOpacity
                    key={sort.key}
                    style={styles.filterSortOption}
                    onPress={() => handleSortChange(sort.key as FilterOptions['sort'])}
                  >
                    <View style={[
                      styles.filterSortRadio,
                      filterOptions.sort === sort.key && styles.filterSortRadioActive
                    ]}>
                      {filterOptions.sort === sort.key && (
                        <View style={styles.filterSortRadioInner} />
                      )}
                    </View>
                    <Text style={styles.filterSortOptionText}>{sort.label}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>

            {/* 操作按钮 */}
            <View style={styles.filterModalActions}>
              <TouchableOpacity
                style={styles.filterModalResetButton}
                onPress={handleResetFilters}
              >
                <Text style={styles.filterModalResetButtonText}>重置</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.filterModalApplyButton}
                onPress={() => {
                  setIsFilterModalVisible(false);
                }}
              >
                <LinearGradient
                  colors={['#6366f1', '#8b5cf6']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                  style={styles.filterModalApplyButtonGradient}
                >
                  <Text style={styles.filterModalApplyButtonText}>应用</Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

export default MyInitiatedScreen;

